const express = require('express');
const path = require("path");
const app = express();
const cors = require('cors')
const joi = require('joi')
const { secretKey } = require('./config')
app.use(cors())
const bodyParse = require('body-parser')
app.use(bodyParse.urlencoded({ extended: false }));
app.use(bodyParse.json())
app.use(express.static(path.join(__dirname, 'uploads')));

app.use((req, res, next) => {
  res.cc = function (err, status = 400, data) {
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
      success: status == 200 ? true : false,
      data
    })
  }
  next();
})

// 解析jwt
const { expressjwt } = require('express-jwt');
// 指定哪些path不需要token身份验证
app.use(expressjwt({ secret: secretKey, algorithms: ['HS256'] }).unless({ path: [/^\/api\//] }))

const userRouter = require('./router/user')
app.use('/api', userRouter)
const menuRouter = require('./router/menu')
app.use('/menu', menuRouter)
const InfoRouter = require('./router/userinfo')
app.use('/my', InfoRouter);
const NoveRouter = require('./router/userinfo')
app.use('/my', NoveRouter);
const cheerioRouter = require('./router/cheerio')
app.use('/my', cheerioRouter);
const doorWayRouter = require('./router/doorWay')
app.use('/my', doorWayRouter);

// const cheerio = require("./cheerio/cheerio")
// cheerio.getNovalData();





app.use((err, req, res, next) => {
  // console.log(err);
  if (err instanceof joi.ValidationError) return res.cc(err);
  res.cc(err.message)
  next();
})

app.listen('8081', () => {
  console.log('serveing is running');
})